import initState from './initState'
import { compilerToFunction } from './compiler/index'
import { callHook, mountComponent } from './lifecycle'
import { mergeOptions } from './utils/index';

export function initMixin(Vue) {
  Vue.prototype._init = function (options) {
    let vm = this;
    this.$options = mergeOptions(this.constructor.options, options);
    // 生命周期hooks beforeCreated
    callHook(vm, 'beforeCreate');
    // 初始化
    initState(this);
    // 生命周期hooks created
    callHook(vm, 'created');
    // 渲染模版
    if (vm.$options.el) {
      vm.$mount(vm.$options.el);
    }
  }
  // 创建$mount
  Vue.prototype.$mount = function (el) {
    let vm = this;
    el = document.querySelector(el);
    vm.$el = el;
    let options = vm.$options;

    if (!options.render) {
      let template = options.template;
      if (!template && el) {
        el = el.outerHTML;
        // dom 转换成 ast语法树
        let render = compilerToFunction(el);
        options.render = render;
      }
    }
    mountComponent(vm, el);
  }
}

